package com.ddwl.goods.service;

import com.ddwl.common.exception.CommonException;
import com.ddwl.common.exception.ExceptionCode;
import com.ddwl.common.util.BeanConverUtils;
import com.ddwl.common.util.MySqlUtil;
import com.ddwl.common.util.ObjectUtil;
import com.ddwl.common.util.UUIDGenerator;
import com.ddwl.goods.dao.ReserveDao;
import com.ddwl.goods.dao.model.Reserve;
import com.ddwl.schema.bo.base.PageBo;
import com.ddwl.schema.bo.goods.ReserveBo;
import com.ddwl.schema.vo.base.PageVo;
import com.ddwl.schema.vo.goods.ReserveVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Fu Zhaohui
 * @version 1.0.0
 * @date 2019/8/15 10:52
 */
@Service
public class ReserveService {

    @Autowired
    private ReserveDao reserveDao;

    public ReserveVo getById(String uid) {
        Reserve entity = reserveDao.selectByPrimaryKey(uid);
        ReserveVo vo = new ReserveVo();
        BeanUtils.copyProperties(entity, vo);
        return vo;
    }

    @Transactional(rollbackFor = Throwable.class)
    public String create(ReserveBo bo) {
        Reserve entity = new Reserve();
        BeanUtils.copyProperties(bo, entity);
        entity.setId(UUIDGenerator.getShortUUID());
        reserveDao.insert(entity);
        return entity.getId();
    }

    @Transactional(rollbackFor = Throwable.class)
    public void update(ReserveBo bo) {
        Reserve entity = reserveDao.selectByPrimaryKey(bo.getId());
        if (entity == null) {
            throw new CommonException(ExceptionCode.DATA_NOT_EXISTS);
        }
        BeanUtils.copyProperties(bo, entity, ObjectUtil.getNullFields(bo));
        reserveDao.updateByPrimaryKeySelective(entity);
    }

    @Transactional(rollbackFor = Throwable.class)
    public void delete(String id) {
        reserveDao.deleteById(id);
    }

    public PageVo<ReserveVo> page(PageBo<ReserveBo> pageBo) {
        PageHelper.startPage(pageBo.getPage(),pageBo.getPageSize(), MySqlUtil.orderBy(pageBo.getSort(),pageBo.isAsc()));
        Reserve reserve = BeanConverUtils.convertBean(pageBo.getParam(),Reserve.class);
        PageInfo info = new PageInfo(reserveDao.select(reserve));
        return new PageVo<>(info.getTotal(),pageBo.getPage(),pageBo.getPageSize(),BeanConverUtils.convertBeanList(info.getList(), ReserveVo.class));
    }
}
